package com.huazhi.wzsnw.util;

import com.huazhi.wzsnw.model.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

public class PathInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session =request.getSession();
        String requestUrl = request.getRequestURI();    //获取请求的URL
        if(requestUrl.endsWith("/rest/login")||requestUrl.indexOf("/rest/login")>=0) {
            return true;
        }
        if(requestUrl.endsWith("/rest/selectByUsernamePassword")||requestUrl.indexOf("/rest/selectByUsernamePassword")>=0) {
            return true;
        }
        // 如果是ajax请求，请求头会有x-requested-with
        String requestWith = request.getHeader("x-requested-with" );
        if (requestWith != null && requestWith.equalsIgnoreCase("XMLHttpRequest" )){
            System.out.println("ajax");
            if (session.getAttribute("userInfo") == null ) {

                response.addHeader("sessionstatus", "timeout");

                return  false ;
            } else  if (session.getAttribute("userInfo") != null ) {
                return  true ;
            }
        } else {
            User user=(User)request.getSession().getAttribute("userInfo");
            if(user==null){
                System.out.println("......................................");
                response.setContentType("text/html");
                response.setCharacterEncoding("utf-8");
                PrintWriter out = response.getWriter();
                StringBuilder builder = new StringBuilder();
                builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
                builder.append("</script>");
                out.print(builder.toString());
                out.close();
                return false;
            }
            return  true ;
        }
        return  false ;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
